//
//  Document.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-7-5.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "Document.h"
#import "Element.h"


@implementation Document

- (NSInteger)nodeType{
	return DOCUMENT_NODE;
}

/**
 * 获取节点名称
 */
- (NSString *)getNodeName{
	return @"#DOCUMENT";
}

/**
 * 通过名称来获取元素
 * 取当前文档中的，所有以 ename命名的一级子元素
 */
-(NSArray *)getElementsByName:(NSString *)ename{
	NSMutableArray *ret = nil;
	int cnum = [childs count];
	if(cnum > 0){
		// TODO 查找以ename命名的子元素
		Node *node;
		NSString *nname;
		ret = [[[NSMutableArray alloc] init] autorelease];
		for (int i = 0; i < cnum; i++) {
			node = (Node *)([childs objectAtIndex:i]);
			NSArray *chds = [node getChildNodes];
			if(chds){
				Node *chd;
				int clen  = [chds count];
				for(int j=0;j<clen;j++){
					chd = (Node *)[chds objectAtIndex:j];
					nname = [chd getNodeName];
					if([nname isEqualToString:ename]){
						[ret addObject:chd];
					}
				}
			}
		}
		if([ret count] == 0){
			ret = nil;
		}
	}
	return ret;
}

/**
 * 获取第一个根节点
 */
-(Element *)rootNode{
	Element *ret = (Element *)[self getFirstChild];
	return ret;
}

/**
 * 查找 xpath 节点 指定 从 根节点开始
 */
-(Element *)query:(NSString *)xpath{
	NSArray *paths = [xpath componentsSeparatedByString:@"/"];
	int con = [paths count];
	Element *ret = nil;
	if(con > 0){
		NSString *ename;
		int len;
		Element *cur = [self rootNode];
		char ch;
		NSArray *chds;
		// 从1 开始，因为 rootNode 已经获取一层了
		for (int i = 1; i<con; i++) {
			ename = [paths objectAtIndex:i];
			len = [ename length];
			if(len > 0){
				ch = [ename characterAtIndex:0];
				int index = 0;
				NSRange range = [ename rangeOfString:@"["];
				if(range.location != NSNotFound){
					int sindex = range.location;
					// TODO 找到了
					NSRange rend = [ename rangeOfString:@"]"];
					range.location = range.location + range.length;
					range.length = rend.location - range.location;
					NSString *substr = [ename substringWithRange:range];
					if(substr){
						index = [substr intValue];
					}
					// 截至  sindex 之前
					ename = [ename substringToIndex:sindex];
				}
				// TODO 做简单一点，就只能够按照顺序搜索
				chds = [cur getElementsByName:ename];
				if(chds){
					if([chds count]>0){
						cur = [chds objectAtIndex:index];
					}
				}else{
					// TODO 没有找到
					cur = nil;
					break;
				}
			}
		}
		ret = cur;
	}
	return ret;
}

-(void)dealloc{
	[super dealloc];
}

@end
